package controller

import (
	"buss"
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin"
	"github.com/robvdl/pongo2gin"
	"io"
	"net/http"
	"os"
	"github.com/cihub/seelog"
	"strconv"
	"encoding/json"
	"time"
	"v1/model"
	"strings"
)

var log  seelog.LoggerInterface
var dao buss.Dao
func Start(port string) {
	log, _ = seelog.LoggerFromConfigAsFile("config/seelog-main.xml")
	defer log.Flush()
	gin.SetMode(gin.ReleaseMode)   //生产模式
	//gin.SetMode(gin.DebugMode)   //调试模式  模版修改直接修改

	router := gin.New()
	router.Use(gin.Logger())   //http 请求日志
	router.Static("/assets", "./assets")
	router.Static("/upload", "./upload")
	router.Static("/tmp", "./tmp")
	pwd, _ := os.Getwd()
	path := pwd + "/templates"
	tmp := pwd + "/tmp"
	router.HTMLRender = pongo2gin.New(pongo2gin.RenderOptions{
		TemplateDir: path,
		ContentType: "text/html; charset=utf-8",
	})
	dao.Init()
	// 测试服务器连通
	router.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK,"active")
	})
	router.GET("/", func(c *gin.Context) {
		config:= dao.QueryForSiteConfig()
		recommends:= dao.QueryForRecommendIconsList()
		recentApps := dao.QueryForRecentIconsList()
		hots:= dao.QueryForHotIconsList()
		allType:=dao.QueryForAllTypeList
		c.HTML(http.StatusOK, "/index/hello.html", pongo2.Context{"title": "world","allType":allType,"recents": recentApps, "recommends": recommends, "hots": hots, "config": config})

	})
	router.GET("/app/detail/:id", func(c *gin.Context) {
		id := c.Param("id")
		detailId ,_:= strconv.Atoi(id)
		go dao.UpdateAppView(detailId)
		config:= dao.QueryForSiteConfig()
		app:= dao.QueryForApp(detailId)
		hots:= dao.QueryForHotIconsList()
		recommendTypes:=dao.QueryForRecommendTypeList()
		var tags map[string]string
		json.Unmarshal([]byte(app.Tags),&tags)
	 	var screenshots map[string]string
		json.Unmarshal([]byte(app.Screenshots),&screenshots)
		c.HTML(http.StatusOK, "/index/detail.html", pongo2.Context{"title": "world", "app": app, "hots": hots,"recommendTypes":recommendTypes,"config": config,"tags":tags,"screenshots":screenshots})
	})
	 router.GET("/app/publish", func(c *gin.Context) {
		 config:= dao.QueryForSiteConfig()
		 categories:= dao.QueryForAllTypeList()
		c.HTML(http.StatusOK, "/index/publish.html", pongo2.Context{"categories": categories, "config": config})
	})
	router.GET("/about", func(c *gin.Context) {
		config:= dao.QueryForSiteConfig()
		c.HTML(http.StatusOK, "/index/about.html", pongo2.Context{"config": config})
	})
	router.GET("/login", func(c *gin.Context) {
		 //自行实现逻辑
	})
	router.GET("/register", func(c *gin.Context) {
		//自行实现逻辑
	})
	router.POST("/manage/upload/doUpload", func(c *gin.Context) {
		file, header, err := c.Request.FormFile("file")
		if err != nil {
			log.Error(err)
		}
		filename := header.Filename
		log.Infof("%s", header.Filename)
		out, err := os.Create(tmp + "/" + filename)
		if err != nil {
			log.Error(err)
		}
		defer out.Close()
		_, err = io.Copy(out, file)
		if err != nil {
			log.Error(err)
		}
		previewFile := "/tmp/" + filename
		c.JSON(http.StatusOK, gin.H{"statusCode": 200, "message": "", "filename": previewFile})

	})
         router.POST("/app/result", func(c *gin.Context) {

		var form model.PublishForm
		// in this case proper binding will be automatically selected
		if c.Bind(&form) == nil {
			if form.AppErcode == "" {
				c.JSON(200, gin.H{"code": -1, "message": "名字不能为空"})
			}
			if len(form.AppName) > 50 {
				c.JSON(200, gin.H{"code": -1, "message": "名字不能超过50个字符"})

			}
			if form.AppIntroduce == "" {
				c.JSON(200, gin.H{"code": -1, "message": "介绍不能为空"})

			}
			if form.AppErcode == "" {
				c.JSON(200, gin.H{"code": -1, "message": "请上传二维码"})

			}
			if form.AppIco == "" {
				c.JSON(200, gin.H{"code": -1, "message": "请上传ICO图片"})

			}
			//c.JSON(200, gin.H{"code": 1, "message":"小程序提交成功,请等待管理员审核"})
			isExist := dao.QueryAppByName(strings.TrimSpace(form.AppName))
			if isExist {
				c.JSON(200, gin.H{"code": -1, "message": "名字已存在"})
			} else {
				var appExt buss.AppExtInfo
				appExt.CreateDate = time.Now().Format("2016-01-02 15:04:05")
				appExt.Name = form.AppName
				appExt.ErCode = form.AppPic1
				appExt.Ico = form.AppIco
				appExt.Tags = form.AppTags
				appExt.Introduce = form.AppIntroduce
				appExt.Url = ""
				appExt.View = 0
				appExt.Status = -1
				appExt.Recommend = 1
				ok := dao.SaveApp(appExt)
				if ok {
					c.JSON(http.StatusOK, gin.H{"code": 1, "message": "小程序提交成功,请等待管理员审核"})
				} else {
					c.JSON(http.StatusOK, gin.H{"code": 1, "message": "小程序提交失败，请联系管理员"})
				}
			}
		}
	})
	router.GET("/app/list/type-:category", func(c *gin.Context) {
		category := c.Param("category")
		number := c.DefaultQuery("page", "1")
		num, err := strconv.Atoi(number)
		if err != nil {
			c.Redirect(http.StatusInternalServerError, "")
		}
		config:= dao.QueryForSiteConfig()
		typeId, err := strconv.Atoi(category)
		if err != nil {
			c.Redirect(http.StatusInternalServerError, "")
		}
		recommends:= dao.QueryForRecommendIconsList()
		allType:=dao.QueryForAllTypeList
		apps := dao.QueryForIconsListByType(typeId, num, 24)
		pageSize, typeName := dao.QueryForCountByType(typeId, 24)
		c.HTML(http.StatusOK, "/index/list.html", pongo2.Context{"title": "world", "type": category, "apps": apps, "pageNumber": num, "totalPage": pageSize, "typeName": typeName, "config": config,"recommends":recommends,"allType":allType})
	})
	router.Run(":"+port)
}
